<script setup lang="ts">
import { onMounted, ref, watch } from "vue"
import { CirclePlus } from "@element-plus/icons-vue"
import { cloneDeep } from "lodash-es"
import { ElMessage, ElMessageBox, FormInstance, FormRules } from "element-plus"
import { RefreshRight, TopRight, Delete } from "@element-plus/icons-vue"

import jsonData from "#/index.json"
import { usePagination } from "@/hooks/usePagination"
import { deletePosition, getPositionInformation, publishPosition } from "@/api/position"
import {
  PositionDetails,
  AppendPositionParams,
  UpdatePositionFormParams,
  QueryPositionFormParams
} from "@/api/position/type"
import { addressCascaderOpts, getAddressDetails, transformAddressToString } from "@/utils/transform"
import { useRouter } from "vue-router"

const loading = ref(false)
const router = useRouter()

// #region 发布岗位
const DEFAULT_FORM_DATA: UpdatePositionFormParams = {
  id: "",
  studyingExperience: undefined as any,
  workAddress: [] as any,
  workDescription: "",
  workPrice: undefined as any,
  workTime: undefined as any,
  workName: ""
}
const dialogVisiable = ref(false)
const dialogFormRef = ref<FormInstance | null>()
const dialogFormData = ref(cloneDeep(DEFAULT_FORM_DATA))
const dialogFormRules: FormRules = {
  workName: [{ type: "string", required: true, min: 2, max: 20, message: "请输入职位名称", trigger: "blur" }],
  studyingExperience: [
    { type: "number", required: true, min: 0, max: 6, message: "请输入正确的学历", trigger: "change" }
  ],
  workAddress: [
    {
      trigger: "change",
      required: true,
      validator: (rule, val, cb) => {
        if (
          Object.prototype.toString.call(val) === "[object Array]" &&
          val.length <= 3 &&
          val.every((li: any) => typeof Number(li) === "number")
        ) {
          cb()
        } else {
          cb("工作地址不正确")
        }
      }
    }
  ],
  workDescription: [
    {
      type: "string",
      required: true,
      min: 20,
      max: 700,
      trigger: "blur",
      message: "工作描述至少20个字，至多不超过700字"
    }
  ],
  workPrice: [{ type: "number", required: true, min: 1, max: 6, message: "请输入正确的薪资范围", trigger: "change" }],
  workTime: [{ type: "number", required: true, min: 0, max: 5, message: "请输入正确的工作经验范围", trigger: "change" }]
}

function resetForm() {
  dialogFormRef.value?.clearValidate()
  dialogFormData.value = cloneDeep(DEFAULT_FORM_DATA)
}

function handlePublish() {
  dialogFormRef.value?.validate((valid: boolean, fields) => {
    if (!valid) return console.error("表单校验不通过", fields)
    const data = {
      ...dialogFormData.value,
      id: dialogFormData.value.id === "" ? undefined : dialogFormData.value.id,
      workAddress: transformAddressToString(dialogFormData.value.workAddress || [])
    }
    publishPosition(data as AppendPositionParams | UpdatePositionFormParams).then(() => {
      ElMessage.success("操作成功")
      dialogVisiable.value = false
      getPositionData()
    })
  })
}
// #endregion

// #region 查询岗位
const DEFAULT_SEARCH_PARAMS: QueryPositionFormParams = {
  studyingExperience: undefined,
  workAddress: [] as [string?, string?, string?],
  workPrice: undefined,
  workName: "",
  workTime: undefined
}
const cascaderOpts = ref()
const searchFormRef = ref<FormInstance | null>()
const searchFormData = ref(cloneDeep(DEFAULT_SEARCH_PARAMS))
const searchFormRules: FormRules = {
  workName: [{ type: "string" }],
  studyingExperience: [
    {
      trigger: "change",
      validator: (rule, val, cb) => {
        if ([undefined, 0, 1, 2, 3, 4, 5, 6].includes(val)) {
          cb()
        } else {
          cb("请选择正确的学历选项")
        }
      }
    }
  ],
  workTime: [
    {
      trigger: "change",
      validator: (rule, val, cb) => {
        if ([undefined, 0, 1, 2, 3, 4, 5].includes(val)) {
          cb()
        } else {
          cb("请选择正确的工作经验范围")
        }
      }
    }
  ],
  workAddress: [
    {
      type: "array",
      trigger: "change",
      validator: (rule, val, cb) => {
        if (val === undefined || (Array.isArray(val) && [0, 1, 2, 3].includes(val.length))) {
          cb()
        } else {
          cb("您选择的工作区域地址不正确")
        }
      }
    }
  ],
  workMinPrice: [
    {
      type: "number",
      trigger: "blur",
      message: "你输入的期望最少工资不正确"
    }
  ],
  workMaxPrice: [
    {
      type: "number",
      trigger: "blur",
      message: "你输入的期望最多工资不正确"
    }
  ]
}
const { paginationData, handleCurrentChange } = usePagination({
  current: 1,
  layout: "total, prev, pager, next, jumper"
})
const listData = ref<PositionDetails[]>([])

function getPositionData(current = 1) {
  const paginationParams = {
    current: paginationData.current,
    pageSize: paginationData.pageSize,
    sortOrder: "desc",
    sortField: "createTime"
  }
  const fixedParams = {
    isCompany: true,
    current,
    workAddress: transformAddressToString(searchFormData.value.workAddress || [])
  }
  getPositionInformation({ ...searchFormData.value, ...fixedParams, ...paginationParams }).then(({ data }) => {
    listData.value = data.records
    paginationData.total = Number(data.total)
  })
}

const getResourceLabel = (val: number | string, resource: { value: number; label: string }[]) => {
  if (val === undefined) val = "1"
  const [tagItem] = resource.filter((item) => item.value === Number(val))
  return tagItem.label
}

function resetSearch() {
  searchFormRef.value?.resetFields()
  getPositionData()
}

watch(
  () => paginationData.current,
  (cur) => {
    getPositionData(cur)
  }
)

onMounted(() => {
  cascaderOpts.value = addressCascaderOpts
  getPositionData()
})

// #endregion

// #region 删除岗位
function handleDelete(data: PositionDetails) {
  ElMessageBox.confirm(`正在删除 ${data.workName} 岗位，确认删除？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    deletePosition(Number(data.id)).then(() => {
      ElMessage({ type: "success", message: "删除成功" })
      getPositionData()
    })
  })
}
// #endregion
</script>

<template>
  <div class="app-container">
    <el-card class="search-card" shadow="never">
      <el-form ref="searchFormRef" :model="searchFormData" :rules="searchFormRules" :inline="true">
        <el-form-item label="职位名称" prop="workName">
          <el-input v-model="searchFormData.workName" style="width: 170px" placeholder="请输入职位名称" clearable />
        </el-form-item>
        <el-form-item label="学历" prop="studyingExperience">
          <el-select
            v-model="searchFormData.studyingExperience"
            style="width: 130px"
            placeholder="请选择学历"
            clearable
          >
            <el-option
              v-for="{ value, label } in jsonData.studyacademicDegree"
              :key="value"
              :label="label"
              :value="value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="工作经验" prop="workTime">
          <el-select v-model="searchFormData.workTime" style="width: 170px" placeholder="请选择工作经验范围" clearable>
            <el-option v-for="{ value, label } in jsonData.workTime" :key="value" :label="label" :value="value" />
          </el-select>
        </el-form-item>
        <el-form-item label="工作区域" prop="workAddress">
          <el-cascader
            :options="cascaderOpts"
            v-model="searchFormData.workAddress as any"
            style="width: 320px"
            clearable
          />
        </el-form-item>
        <el-form-item label="薪资范围" prop="workPrice">
          <el-select v-model="searchFormData.workPrice" placeholder="请选择薪资范围" style="width: 200px" clearable>
            <el-option v-for="{ label, value } in jsonData.workPrice" :key="value" :value="value" :label="label" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getPositionData()">筛选</el-button>
          <el-button plain @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card class="post-card" v-loading="loading" shadow="never">
      <div class="toolbar-wrapper">
        <div>
          <el-button type="primary" :icon="CirclePlus" @click="dialogVisiable = true">发布岗位</el-button>
        </div>
        <div>
          <el-tooltip content="刷新当前页">
            <el-button type="primary" :icon="RefreshRight" circle @click="getPositionData()" />
          </el-tooltip>
        </div>
      </div>
      <div class="post-wrapper">
        <el-card class="position-card" v-for="pos in listData" :key="pos.id" shadow="hover">
          <template #header>
            <div class="card-header">
              <el-row justify="space-between">
                <el-col :span="14">
                  <el-text class="fw-700" type="primary" size="large">{{ pos.workName }}</el-text>
                </el-col>
                <el-col :span="10">
                  <el-text type="info">薪资范围</el-text>
                  &nbsp;
                  <el-text>{{ getResourceLabel(pos.workPrice!, jsonData.workPrice) }}</el-text>
                </el-col>
              </el-row>
            </div>
          </template>
          <div class="card-content">
            <div class="work">
              <el-text class="fw-700">工作描述</el-text>
              <div class="work-details" v-html="pos.workDescription" />
            </div>
            <div class="work-tag">
              <div class="flex gap-2">
                <el-tag class="academic-degree" type="info">{{
                  getResourceLabel(String(pos.studyingExperience), jsonData.studyacademicDegree)
                }}</el-tag>
                <el-tag class="work-experience" type="info">
                  {{ getResourceLabel(String(pos.workTime), jsonData.workTime) }}
                </el-tag>
              </div>
            </div>
          </div>
          <template #footer>
            <el-row justify="space-between" align="middle">
              <el-col :span="18">
                <div>
                  <span class="company">
                    <svg-icon name="company" />
                    {{ pos.companyVO.companyShortName }}
                  </span>
                  &nbsp;
                  <span v-show="Array.isArray(pos.workAddress) && pos.workAddress.length !== 0" class="address">
                    <svg-icon name="address" />
                    <span style="font-size: 14px">{{ getAddressDetails(pos.workAddress) }}</span>
                  </span>
                </div>
              </el-col>
              <el-col :span="6">
                <el-tooltip content="查看详情" placement="bottom" effect="light">
                  <el-button :icon="TopRight" @click="router.push(`/post-details/${pos.id}`)" plain circle />
                </el-tooltip>
                <el-tooltip content="删除" placement="bottom" effect="light">
                  <el-button type="danger" :icon="Delete" @click="handleDelete(pos)" circle />
                </el-tooltip>
              </el-col>
            </el-row>
          </template>
        </el-card>
      </div>
      <div class="pager-wrapper">
        <el-pagination
          background
          :layout="paginationData.layout"
          :total="paginationData.total"
          :page-size="paginationData.pageSize"
          :current-page="paginationData.current"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <el-dialog
      v-model="dialogVisiable"
      :title="dialogFormData.id ? '修改岗位' : '发布岗位'"
      @close="resetForm"
      width="50%"
    >
      <el-form
        ref="dialogFormRef"
        :model="dialogFormData"
        :rules="dialogFormRules"
        label-width="80px"
        label-position="left"
      >
        <el-form-item prop="workName" label="职位名称">
          <el-input v-model="dialogFormData.workName" placeholder="请输入职位名称" style="width: 400px" />
        </el-form-item>
        <el-form-item prop="studyingExperience" label="学历">
          <el-select v-model="dialogFormData.studyingExperience" style="width: 200px" clearable>
            <el-option
              v-for="{ label, value } in jsonData.studyacademicDegree"
              :key="value"
              :label="label"
              :value="value"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="workAddress" label="工作地址" style="width: 300px" clearable>
          <el-cascader v-model="dialogFormData.workAddress as any" :options="cascaderOpts" />
        </el-form-item>
        <el-form-item prop="workDescription" label="工作描述">
          <el-input
            v-model="dialogFormData.workDescription"
            type="textarea"
            style="width: 500px"
            :rows="4"
            placeholder="请输入工作描述"
          />
        </el-form-item>
        <el-form-item prop="workPrice" label="薪资范围">
          <el-select v-model="dialogFormData.workPrice" placeholder="请选择薪资范围" style="width: 200px" clearable>
            <el-option v-for="{ label, value } in jsonData.workPrice" :key="value" :value="value" :label="label" />
          </el-select>
        </el-form-item>
        <el-form-item prop="workTime" label="工作经验">
          <el-select v-model="dialogFormData.workTime" style="width: 170px" placeholder="请选择工作经验范围" clearable>
            <el-option v-for="{ value, label } in jsonData.workTime" :key="value" :label="label" :value="value" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="handlePublish">发布岗位</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss" src="./style.scss"></style>
